package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.mq.NewsAutoScanConstants;
import com.heima.common.constants.mq.NewsUpOrDownConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.thread.WmThreadLocalUtils;
import com.heima.model.wemedia.vo.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String website;
    @Resource
    WmMaterialMapper wmMaterialMapper;
    @Resource
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Resource
    WmNewsMapper wmNewsMapper;
    @Resource
    WmUserMapper wmUserMapper;
    @Autowired
    RabbitTemplate template;

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
//        校验参数
        if (dto == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
//        获取当前用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
//        条件查询
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword());
        wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        wrapper.eq(dto.getStatus()!=null, WmNews::getStatus,dto.getStatus());
        wrapper.ge(dto.getBeginPubDate()!=null, WmNews::getCreatedTime,dto.getBeginPubDate())
                .le(dto.getEndPubDate()!=null, WmNews::getCreatedTime, dto.getEndPubDate());
        wrapper.eq(WmNews::getUserId,user.getId());
        wrapper.orderByDesc(WmNews::getCreatedTime);
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> iPage = page(page, wrapper);
        List<WmNews> records = iPage.getRecords();

        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), records);
        result.setHost(website);
        return result;
    }

    @Override
    @Transactional
    public ResponseResult submitNews(WmNewsDTO dto) {
//        参数校验
        if (dto==null || StringUtils.isBlank(dto.getContent()) || StringUtils.isBlank(dto.getTitle())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
//        没有newsId时直接保存
        WmNews wmNews = new WmNews();
        if (dto.getId()==null){
            saveNews(dto,user.getId(),wmNews);
        }else {
//        有newsId时修改原news
            wmNews = getById(dto.getId());
            if (wmNews == null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            }
//        清空关联表
            wmNewsMaterialMapper.delete(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            saveNews(dto,user.getId(),wmNews);
        }
//        修改相关数据
        String content = dto.getContent();
        List<Map> list = JSON.parseArray(content, Map.class);
//        将正文内容取出图片信息，去重，去除前缀，合并为list
        List<String> collect = list.stream().filter(o -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(o.get("type")))
                .map(o -> o.get("value").toString())
                .map(o -> o.replaceAll(website, ""))
                .distinct()
                .collect(Collectors.toList());
//        检查图片是否失效
        List<Integer> urlIds = wmMaterialMapper.getIdByUserIdAndUrl(user.getId(), collect);
        if (collect.size()>urlIds.size()){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"文章中有图片失效");
        }
        wmNewsMaterialMapper.saveUrls(urlIds,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        if (wmNews.getType() == null){
            if (collect.size()==0){
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }else if (collect.size()>2){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                String images = collect.stream().limit(3).map(i->i.replaceAll(website,"")).collect(Collectors.joining(","));
                List<Integer> urls = wmMaterialMapper.getIdByUserIdAndUrl(user.getId(), collect.stream().limit(3).map(i -> i.replaceAll(website, "")).collect(Collectors.toList()));
                wmNewsMaterialMapper.saveUrls( urls,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
                wmNews.setImages(images);

            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                String images = collect.stream().limit(1).map(i->i.replaceAll(website,"")).collect(Collectors.joining(","));
                List<Integer> urls = wmMaterialMapper.getIdByUserIdAndUrl(user.getId(), collect.stream().limit(1).map(i -> i.replaceAll(website, "")).collect(Collectors.toList()));
                wmNewsMaterialMapper.saveUrls( urls,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
                wmNews.setImages(images);
            }
            updateById(wmNews);
        }
        template.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(website);
        return result;
    }

    @Override
    public ResponseResult deleteWmNewsById(Integer id) {
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus()) && WemediaConstants.WM_NEWS_UP.equals(wmNews.getEnable())){
            CustException.cust(AppHttpCodeEnum.ADMING_CHANNEL_STATUS_TRUE);
        }
        wmNewsMaterialMapper.delete(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getNewsId,id));
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        if (dto == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = new WmNews();
        wmNews.setId(dto.getId());
        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);
        WmNews news = getById(dto.getId());
        if (dto.getEnable()==0){
            template.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,news.getArticleId());
        }else {
            template.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,news.getArticleId());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findListVO(NewsAuthDTO dto) {
        if (dto == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        String title = dto.getTitle();
        Short status = dto.getStatus();
        dto.checkParam();

        List<WmNewsVO> wmNewsVOList = wmNewsMapper.getVO(title, status, (dto.getPage()-1)*dto.getSize(), dto.getSize());
        Long count = wmNewsMapper.getCount(title, status);
        return new PageResponseResult(dto.getPage(),dto.getSize(),count,wmNewsVOList);
    }

    @Override
    public ResponseResult findOneVO(Integer id) {
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wmUserMapper.selectById(userId);
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVO);
        wmNewsVO.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(wmNewsVO);
    }

    @Override
    public ResponseResult updateNews(NewsAuthDTO dto, Short wmNewsManualedStatus) {
        if (dto == null || dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer id = dto.getId();
        WmNews wmNews = getById(id);
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmNews.setStatus(wmNewsManualedStatus);
        if (StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult();
    }


    private void saveNews(WmNewsDTO dto, Integer id,WmNews wmNews) {
        BeanUtils.copyProperties(dto,wmNews);
        wmNews.setUserId(id);
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        wmNews.setSubmitedTime(new Date());
        if (dto.getImages().size()>0){
            List<String> images = dto.getImages();
            String image = images.stream()
                    .map(i->i.replaceAll(website,""))
                    .collect(Collectors.joining(","));
            wmNews.setImages(image);
        }
        if (dto.getType().intValue() == WemediaConstants.WM_NEWS_TYPE_AUTO){
            wmNews.setType(null);
        }
        saveOrUpdate(wmNews);
    }



}
